package com.emser.unc.activitys;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.StringTokenizer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.emser.unc.R;
import com.emser.unc.activitys.resources.Constant;
import com.emser.unc.database.dao.CustomerDataSource;
import com.emser.unc.restlet.manager.NoSaleReportTransferManager;
import com.emser.unc.serializable.CustomerDTO;
import com.emser.unc.serializable.NoSaleReportDTO;

@SuppressLint("HandlerLeak")
public class NoSaleReportActivity extends Activity implements OnClickListener,
		Runnable {
	/** Called when the activity is first created. */

	private Spinner spinner1 = null;
	private HashMap<String, String> hashMap = null;
	private EditText ed = null;
	private Button btnAccept;
	private Button btnCancel;
	private Handler handler;
	private ProgressDialog progressDialog;
	private AlertDialog alertDialog;
	private Boolean dispatched;
	private CustomerDataSource datasource;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.m_no_sale_report);
		initDatasource();
		initItems();
		captureSpinner();
		initWidgets();
		initHandler();
		addDialogListener();
		

		/* Implementacion de la busqueda en el spinner */
		ed = (EditText) findViewById(R.id.editText1);

		ed.addTextChangedListener(new TextWatcher() {

			public void afterTextChanged(Editable arg0) {
				// TODO Auto-generated method stub
				serchString(ed.getText().toString());
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
			}
		});
		/* Implementacion de la busqueda en el spinner */
		ed.setOnFocusChangeListener(new View.OnFocusChangeListener() {

			public void onFocusChange(View v, boolean hasFocus) {
				// TODO Auto-generated method stub
				if (hasFocus) {
					ed.selectAll();
				}
			}

		});
	}
	
	private void initDatasource() {
		datasource = new CustomerDataSource(this);
		datasource.open();
	}

	private void initItems() {
		hashMap = new HashMap<String, String>();
		hashMap.put("*", "Seleccione Motivo - *");
		hashMap.put("1", "Cerrado");
		hashMap.put("2", "Sin dinero");
		hashMap.put("3", "No esta el comprador");
		hashMap.put("4", "No quiere servicio");

		String[] dato = new String[hashMap.size()];
		Integer i = 0;

		for (Iterator<String> it = hashMap.keySet().iterator(); it.hasNext();) {
			String s = (String) it.next();
			String s1 = (String) hashMap.get(s);
			dato[i] = (s + " - " + s1);
			i++;
		}

		ArrayList<String> lista = new ArrayList<String>();

		for (i = 0; i < dato.length; i++)
			lista.add(dato[i]);

		Collections.sort(lista);

		for (i = 0; i < dato.length; i++)
			dato[i] = lista.get(i).toString();

		ArrayAdapter<String> adaptador = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, dato);

		spinner1 = (Spinner) findViewById(R.id.spinner1);

		adaptador
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner1.setAdapter(adaptador);
		dispatched = Boolean.FALSE;
	}

	private void serchString(String data) {
		if (hashMap.containsKey(data)) {
			Integer selection = Integer.parseInt(data);
			spinner1.setSelection(selection);
		}
		if ((data == null) || (data.equals(""))) {
			spinner1.setSelection(0);
		}
	}

	private void captureSpinner() {
		spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parent,
					android.view.View v, int position, long id) {
				try {
					Object item = parent.getItemAtPosition(position);
					StringTokenizer st = new StringTokenizer(item.toString(),
							" ");
					String toShow = st.nextElement().toString();
					if (!toShow.equals("*")) {
						ed.setText(toShow);
						ed.clearFocus();
					}

					else {
						ed.setText("");
						ed.clearFocus();
					}

				} catch (Exception e) {
					Toast.makeText(getBaseContext(),
							"No hay elementos en el spinner".toString(),
							Toast.LENGTH_SHORT).show();
				}
			}

			public void onNothingSelected(AdapterView<?> parent) {
			}
		});

	}

	private void initWidgets() {
		btnAccept = (Button) findViewById(R.id.buttonAccept);
		btnAccept.setOnClickListener(this);
		btnCancel = (Button) findViewById(R.id.buttonCancel);
		btnCancel.setOnClickListener(this);
		alertDialog = new AlertDialog.Builder(this).create();
		CustomerDTO c = datasource.getCustomerById(getIntent().getLongExtra("customerId", -1));
		TextView cCode = (TextView) findViewById(R.id.textView3);
		TextView cName = (TextView) findViewById(R.id.textViewName);
		TextView cAddress = (TextView) findViewById(R.id.textView7);
		if (c != null){
			cCode.setText(c.getCode().toString());
			cName.setText(c.getLastName()+", "+c.getFirstName());
			cAddress.setText(c.getAddress());
		}
	}

	private void initHandler() {
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				progressDialog.dismiss();
				switch (msg.what) {
				case Constant.H_SEND_CASE:
					if(dispatched){
						alertDialog.setMessage("Enviado con exito");
						alertDialog.show();
					}
					else{
						alertDialog.setMessage("Fallo en envio: Reintente");
						alertDialog.show();
					}
					break;
				case Constant.H_ERROR_CASE:
					 alertDialog
					 .setMessage(getString(R.string.login_alert_dialog_error));
					 alertDialog.show();
					break;
				default:
					super.handleMessage(msg);
					break;
				}
				dispatched = Boolean.FALSE;
			}
		};
	}
	
	private void addDialogListener() {
		alertDialog.setButton(getString(R.string.login_alert_dialog_button),
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						return;
					}
				});
	}
	@Override
	protected void onResume() {
		datasource.open();
		super.onResume();
	}
	
	@Override
	protected void onPause() {
		datasource.close();
		super.onPause();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.buttonAccept:
			onSendNoSaleReport();
//			finish();
			break;
		case R.id.buttonCancel:
			finish();
			break;
		default:
			break;
		}
	}

	private void onSendNoSaleReport() {
		progressDialog = ProgressDialog.show(NoSaleReportActivity.this,
				getString(R.string.report_process_dialog_title),
				getString(R.string.report_process_dialog_get), true, false);
		Thread thread = new Thread(this);
		thread.start();
	}

	private void startNoSaleTransfer() throws Exception {
		NoSaleReportDTO noSaleReportDTO = new NoSaleReportDTO();
		Long code = spinner1.getSelectedItemId();
		noSaleReportDTO.setCode(code.intValue());
		noSaleReportDTO.setCustomerID(getIntent().getLongExtra("customerId", -1));
		noSaleReportDTO.setSellerUserName(getIntent().getStringExtra("sellerName"));
		System.out.println("noSaleReportDTO.getIdReport() "+noSaleReportDTO.getIdReport());
		System.out.println("noSaleReportDTO.getSellerUserName() "+noSaleReportDTO.getSellerUserName());
		System.out.println("noSaleReportDTO.getCustomerID() "+noSaleReportDTO.getCustomerID());
		
		NoSaleReportTransferManager nsrtm = new NoSaleReportTransferManager();
		nsrtm.setParams(getString(R.string.restlet_url_nosale),
				getString(R.string.restlet_user),
				getString(R.string.restlet_pass));
		ExecutorService executor = Executors.newSingleThreadExecutor();
		Future<String> future = executor.submit(nsrtm);
		nsrtm.setRequest(noSaleReportDTO);
		future.get(30, TimeUnit.SECONDS);
		dispatched = (Boolean) nsrtm.getResponse();
		
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			startNoSaleTransfer();
			System.out.println("LLEGO A ESTE PUNTO  8888888888888888888");
			handler.sendEmptyMessage(Constant.H_SEND_CASE);
		} catch (Exception e) {
			System.out.println(e.getMessage());
			handler.sendEmptyMessage(Constant.H_ERROR_CASE);
		}

	}

}
